package databasetest;

import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.text.DecimalFormat;
import java.util.Vector;

import javax.swing.JInternalFrame;

import java.awt.BorderLayout;

import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

public class Select extends JInternalFrame {
	Connection conn; 
	DataBaseTest main;
	private JPanel panel;
	private JTextField cmd;
	private JButton search;
	private JLabel result;
	private JScrollPane scrollPane;
	private JTable table;
	DefaultTableModel model; // Jtable에 뿌려줄 모델;



	public Select(Connection conn,DataBaseTest d) {
		super("조회", true, true, true, true);
		addInternalFrameListener(new InternalFrameAdapter() {
			@Override
			public void internalFrameClosing(InternalFrameEvent arg0) {

				if(model != null){
					model.setRowCount(0);
					model.setColumnCount(0);
				}

				cmd.setText("");


			}

		});
		this.conn = conn;
		this.main = d;
		setBounds(100, 400, 450, 300);
		getContentPane().setLayout(new BorderLayout(0, 0));
		getContentPane().add(getPanel(), BorderLayout.NORTH);
		getContentPane().add(getResult(), BorderLayout.SOUTH);
		getContentPane().add(getScrollPane(), BorderLayout.CENTER);


		JTableHeader jh1 = table.getTableHeader();
		jh1.setReorderingAllowed(false);//컬럼 이동 금지
	}

	public void search() { // 검색 메소드.

		try {
			String sql = cmd.getText(); // 입력상자 sql로 저장
			PreparedStatement pstmt = conn.prepareStatement(sql); // get한 문구를 콘을
			// 통해서 가져온다.
			ResultSet rs = pstmt.executeQuery(); // 조회된 내용을 rs에 담는다.

			ResultSetMetaData rsmd  = rs.getMetaData(); // 데이타(테이블) 의 구조
			Vector<String> col = new Vector<String>(); // dbms에서 가져온 값을 담을 백터.
			col.add("NO"); 

			// 컬럼명 얻어오기.
			for(int i=1;i<=rsmd.getColumnCount();i++){
				col.add(rsmd.getColumnName(i));
			}
			model = new DefaultTableModel(col,0);

			int cnt = 1;
			while (rs.next()) {

				Vector vec = new Vector();
				vec.add(cnt);
				for (int i = 1; i <= rsmd.getColumnCount(); i++) { // 컬럼의 길이까지
					vec.add("" + rs.getString(i)); // 1,2,3, i 번째 컬럼의 데이터값 가져오기
				}
				model.addRow(vec); // 로우 추가
				cnt++;
			}
			table.setModel(model);
			rs.close();
			pstmt.close();

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.add(getCmd());
			panel.add(getSearch());
		}
		return panel;
	}

	private JTextField getCmd() {
		if (cmd == null) {
			cmd = new JTextField();
			cmd.setColumns(27);
		}
		return cmd;
	}

	private JButton getSearch() {
		if (search == null) {
			search = new JButton("쿼리실행");
			search.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					search();

				}
			});
		}
		return search;
	}

	private JLabel getResult() {
		if (result == null) {
			result = new JLabel("New label");
		}
		return result;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}

	private JTable getTable() {
		if (table == null) {
			table = new JTable();
			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseReleased(MouseEvent arg0) {
					if(main.update==null){
						main.openUpdate();
					}

					int row = table.getSelectedRow(); //클릭하여 가져온 행
					String s =(String)table.getValueAt(row, 1); // 가져온 행의 1번째 칼럼
					String c =(String)table.getValueAt(row, 2); // 가져온 행의 2번째 칼럼
					String e =(String)table.getValueAt(row, 3); // 가져온 행의 3번째 칼럼

					main.update.setData(s, c, e);
					if(main.update.isVisible()==false){
                        main.contentPane.add(main.update);
					}
					main.update.setVisible(true);
					main.update.toFront();

					main.delete.setData(s, c, e);
					if(main.update.isVisible()==false){
                        main.contentPane.add(main.delete);
					}
					main.delete.setVisible(true);
					main.delete.toFront();
				}
			});
		}
		return table;
	}
}
